let BaseController = require('./BaseController')
let fs = require('fs')
let path = require('path')
class Controller extends BaseController {
    constructor() {
        super();
        this.baseSrc = `d:/数据指标分类/${new Date().format('yyyyMMdd')}/待入库/05日主力/沪深两市实时资金流向/`;
        this.encode = 'UTF-8'
        this.params = {
            pageIndex: 1,
            date: new Date().format('yyyy-MM-dd')
        }
        this.pageTotal = '';
        this.data = []
    }
    /**
     * 获取url
     */
    getUrl(date) {
        //http://data.eastmoney.com/zjlx/detail.html
        return `http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?type=ct&st=(BalFlowMain)&sr=-1&p=${this.params.pageIndex}&ps=50&js=var%20ibqySkcp={pages:(pc),date:%222014-10-22%22,data:[(x)]}&token=894050c76af8597a853f5b408b759f5d&cmd=C._SZAME&sty=DCFFITA&rt=51106621`
    }

    /**
     * 获取历史数据
     */
    async getHistory() {
        console.log('21日主力_沪深两市实时资金流向_深市A股Controller')
        if (this.pageTotal === '' || this.params.pageIndex <= this.pageTotal) {
            console.log(JSON.stringify(this.params))
            let result = await this.getData('', this.isCache)
            result = this.axiosDataFormat(result.toString());
            let pageDate = result.data;
            this.pageTotal = result.pages||0
            this.params.pageTotal = this.pageTotal;
            this.data.push(pageDate.join('\n') + '\n')
            this.params.pageIndex++;
            await this.getHistory()
        }
    }
    /**
     * 数据格式化
     */
    axiosDataFormat(data) {
        let result = null
        try {
            result = JSON.parse(data.replace(/^var\s\w+?\s*\=/, '').trim())
        } catch (err) {
            try {
                result = eval('(' + data.replace(/^var\s\w+?\s*\=/, '').trim() + ')')
            } catch (err) {
                if (data.indexOf('502 Bad Gateway') > -1) {
                    return []
                } else {
                    console.log(err)
                }

            }
        }
        return result
    }

    /**
     * 写csv
     */
    writeCsv(arr) {
        if (!fs.existsSync(this.baseSrc)) {
            this.mkdirs(this.baseSrc)
        }
        if (arr && arr.length) {

            let content = `index,code,name,最新价,今日涨幅,主力净流入净额,主力净流入净占比,超大单净流入净额,超大单净流入净占比,大单净流入净额,大单净流入净占比,中单净流入净额,中单净流入净占比,小单净流入净额,小单净流入净占比,时间,-\n`;
            content += arr.join('\n');
            fs.writeFileSync(path.join(this.baseSrc, `深市A股_${this.params.date.replace(/-/g, '')}.csv`), content, 'UTF-8')
        }
    }

    async main(startDate = '2015-01-01', isCache = true) {
        this.isCache = isCache;
        console.log('--->21日主力_沪深两市实时资金流向_深市A股Controller')
        await this.getHistory()
        this.writeCsv(this.data);
    }
}

let controller = new Controller()
module.exports = controller